package com.ppxkk.city.app;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ppxkk.city.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.security.MessageDigest;



public class OneActivity extends Activity
{
    private TextView UserName;
    private Button LoginBtn,LoginOnlyBtn;
    private SharedPreferences sp;
    private String 接口 = "http://i.agyer.com/user_info.json?type=info";
    private String key = "49ff2878167a5979";
    //后台Key值
    private String token = "1158e285f1cd9871b094fd1f056bb96f";
    private HttpURLConnection h;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        //init views
        UserName = findViewById(R.id.userName);
        LoginBtn = findViewById(R.id.loginButton);
        LoginOnlyBtn = findViewById(R.id.loginOnlyButton);
        //account storage
        sp = getSharedPreferences("user", MODE_PRIVATE);
        String user=sp.getString("user", "");
        LoginBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View p1){
                Toast.makeText(OneActivity.this, (h!=null?h.toString():"")+sp.getString("user", ""), Toast.LENGTH_LONG).show();
                if (h!=null){
                    Toast.makeText(OneActivity.this, "please wait while logging in", Toast.LENGTH_LONG).show();
                    return;
                } else if (sp.getString("user", "")!=""){
                    //log out
                    Editor e=sp.edit();
                    e.remove("user");
                    e.remove("password");
                    e.apply();
                    UserName.setText("not login");
                    LoginBtn.setText("register");
                    LoginOnlyBtn.setVisibility(0);
                    Toast.makeText(OneActivity.this, "logged out", Toast.LENGTH_LONG).show();
                    return;
                }
                //go to login
                Intent i= new Intent();
                i.setClassName(OneActivity.this, "com.ppxkk.city.app.RegisterActivity");
                startActivityForResult(i, 1);
            }
        });
        LoginOnlyBtn.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View p1)
                {
                    Intent i= new Intent();
                    i.setClassName(OneActivity.this, "com.ppxkk.city.app.LoginActivity");
                    startActivityForResult(i, 2);
                }
                
            
        });
        //has logged in?
        if (user == "")
        {
            //not yet logged in
            Toast.makeText(OneActivity.this, "please login first", Toast.LENGTH_LONG).show();
            /*Intent i= new Intent();
            i.setClassName(OneActivity.this, "com.agyer.myapplication.RegisterActivity");
            startActivityForResult(i, 1);*/
            UserName.setText("not login");
            LoginBtn.setText("register");
            LoginOnlyBtn.setVisibility(0);
        }
        else
        {
            //log in already
            //do login api
            login(user,
                  sp.getString("password", "")
                  );
            UserName.setText("logging in");
            LoginBtn.setText("logging in");
            LoginOnlyBtn.setVisibility(8);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==2){
            if (data == null)
            {
                //login cancel
                Toast.makeText(OneActivity.this, "login canceled", Toast.LENGTH_LONG).show();
                return;
            }
            //store account
            String u=data.getStringExtra("user");
            String p=data.getStringExtra("password");
            Editor e=sp.edit();
            e.putString("user", u);
            e.putString("password", p);
            e.apply();
            //do login api
            //login(u, p);
            UserName.setText("login with "+u);
            LoginBtn.setText("log out");
            LoginOnlyBtn.setVisibility(8);
            //Toast.makeText(OneActivity.this, "regist successful,login automatically", Toast.LENGTH_LONG).show();
            
        } else if (requestCode == 1)
        {
            if (data == null)
            {
                //login cancel
                Toast.makeText(OneActivity.this, "register canceled", Toast.LENGTH_LONG).show();
                return;
            }
            //store account
            String u=data.getStringExtra("user");
            String p=data.getStringExtra("password");
            Editor e=sp.edit();
            e.putString("user", u);
            e.putString("password", p);
            e.apply();
            //do login api
            login(u, p);
            //Toast.makeText(OneActivity.this, "regist successful,login automatically", Toast.LENGTH_LONG).show();
        }
    }
    
    private void login(String n, String p)
    {
        if (h != null)
        {
            //cancel previous
            h.disconnect();
            h = null;
        }
        Toast.makeText(OneActivity.this, "logging in", Toast.LENGTH_LONG).show();
        //MD5加密Token -> （key+user+pass+后台token值）
        //Toast.makeText(OneActivity.this, 接口 + "&key=" + key + "&token=" + token + "&user=" + n + "&pass=" + p, Toast.LENGTH_LONG).show();
        new Thread(new HttpRunnable(
                       接口, 
                       key, 
                       n, 
                       p, 
                       hash((key + n + p + token).getBytes())
                   )).start();
    }

    private Handler hd=new Handler(){

        @Override
        public void handleMessage(Message msg)
        {

            super.handleMessage(msg);
            h=null;
            //获取更新来的内容
            Bundle data=msg.getData();
            String message;
            int result=0;
            String jsonString=data.getString("message", "{}");
            try
            {
                //解析js
                JSONObject js=new JSONObject(jsonString);
                result = js.getInt("code");
                //获取message的信息
                message = js.getString("message");
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                message = "access error";
            }
            //Toast.makeText(OneActivity.this, result+message, Toast.LENGTH_LONG).show();
            if (result == 1)
            {
                String user=data.getString("user");
                if (user == null)
                {
                    return;
                }
                UserName.setText("login with " + user);
                LoginBtn.setText("log out");
                LoginOnlyBtn.setVisibility(8);
                Toast.makeText(OneActivity.this, "login successful", Toast.LENGTH_LONG).show();
            }
            else
            {
                UserName.setText("login failed");
                LoginBtn.setText("register");
          //      LoginOnlyBtn.setVisibility(8);
                Toast.makeText(OneActivity.this, "login failed", Toast.LENGTH_LONG).show();
            }
        }

    };

    private class HttpRunnable implements Runnable
    {
        private String api;
        private String key;
        private String user;
        private String pass;
        private String token;

        public HttpRunnable(String api, String key, String user, String pass, String token)
        {
            this.api = api;
            this.key = key;
            this.user = user;
            this.pass = pass;
            this.token = token;
        }

        @Override
        public void run()
        {
            try
            {
                h = (HttpURLConnection) new URL(
                    api + "&key=" + key + "&token=" + token + "&user=" + user + "&pass=" + pass
                ).openConnection(Proxy.NO_PROXY);
                h.setRequestMethod("POST");
                /*h.addRequestProperty("key", this.key);
                 h.addRequestProperty("token", this.token);
                 h.addRequestProperty("user", this.user);
                 h.addRequestProperty("pass", this.pass);*/
                h.setUseCaches(true);
                h.setConnectTimeout(3000);
                h.connect();
                //读取流内容
                InputStream i=h.getInputStream();
                InputStreamReader ir=new InputStreamReader(i);
                BufferedReader br=new BufferedReader(ir);
                StringBuilder sb=new StringBuilder();
                String read;
                //循环读取
                while (true)
                {
                    read = br.readLine();
                    //没有了，跳出循环
                    if (read == null)
                    {
                        break;
                    }
                    sb.append(read);
                }
                h.disconnect();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message",
                                 sb.toString()
                                 );
                bundle.putString("user", user);
                //bundle.putString("pass", pass);
                m.setData(bundle);
                hd.sendMessage(m);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message", 
                                 e.getMessage()
                                 );
                m.setData(bundle);
                hd.sendMessage(m);
            }


        }
    }

    private String hash(byte[] btInput)
    {
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        try
        {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
}
